import os


def codon_usage_to_csv(input_data):
    # 分割每一行
    lines = input_data.strip().split('\n')

    # 输出列表
    output = []
    output.append("codon,amino_acid,frequency")  # 添加CSV的header

    for line in lines:
        # 分割每一行为各个部分
        parts = line.split()

        # 检查是否有足够的数据项
        for i in range(0, len(parts) - 3, 4):
            codon = parts[i]
            amino_acid = parts[i+1]
            frequency = parts[i+2]
            output.append(f"{codon},{amino_acid},{frequency}")

    # 连接所有的输出并返回
    return '\n'.join(output)


def runner(input_file_path, output_file_path):
    with open(input_file_path, 'r') as f:
        data = f.read()

    if not os.path.exists("data"):
        os.mkdir("data")

    csv_output = codon_usage_to_csv(data)

    with open(output_file_path, "w") as f:
        f.write(csv_output)

    print(f"Data saved to {output_file_path}")


if __name__ == "__main__":
    input_file_path = "codon_usage/Drosophila_melanogaster.txt"
    output_file_path = "data/Drosophila_melanogaster.csv"
    runner(input_file_path=input_file_path, output_file_path=output_file_path)
